<template>
  <scroll
    class="suggest"
    :data="result"
    :pullup="pullup"
    @scrollToEnd="searchMore"
    ref="suggest"
    :beforeScroll="beforeScroll"
    @beforeScroll="listScroll"
  >
    <div class="scroll-wrapper">
      <ul class="suggest-list">
        <li
          class="suggest-item"
          v-for="(item,index) in result"
          :key="index"
          @click="SelectItem(item)"
        >
          <div :class="getIconCls(item)">
            <i></i>
          </div>
          <div class="name">
            <p class="text" v-html="getname(item)"></p>
          </div>
        </li>
        <div class="loading">
          <loading v-show="hasMore" title></loading>
        </div>
      </ul>
      <div class="no-result-wrapper" v-show="!hasMore && !result.length">
        <noresult title="抱歉，暂无收缩结果"></noresult>
      </div>
    </div>
  </scroll>
</template>
<script>
import { getSearchResult } from "@/api/search";
import { ERR_OK } from "@/api/config";
import { createResultSong } from "@/common/js/SongObject";
import scroll from "@/base/scroll/scroll";
import loading from "@/base/loading/loading";
import { SingerResult, Singer, getVkey } from "@/common/js/SingerObject";
import { mapMutations, mapActions } from "vuex";
import { getMusicVkey } from "@/api/Singer";
import noresult from "../../base/no-result/no-result";
const TYPE_SINGER = "singer";
const n = 15; //每页展示的数据
export default {
  data() {
    return {
      page: 1, //默认展示当前页面
      result: [], //搜索的结果
      pullup: true, //下拉刷新
      hasMore: true, //可以加载更多的标志位
      changeQuery: false, //标记query是否发生改变
      beforeScroll: true
    };
  },
  props: {
    query: {
      //接收查询的参数
      type: String,
      default: ""
    },
    showSinger: {
      type: Boolean,
      default: true
    }
  },
  computed: {},
  components: {
    scroll,
    loading,
    noresult
  },
  methods: {
    // 请求服务端，抓取检索的数据
    search() {
      if (this.changeQuery) {
        this.page++;
        this.$refs.suggest.scrollTo(0, 0);
      }
      this.hasMore = true;
      getSearchResult(this.query, this.page, this.showSinger, n).then(res => {
        // console.log(res);
        if (res.code === ERR_OK) {
          this.result = this.result.concat(this._normalrizeResult(res.data));
          //   检查是否还有更多的数据
          this.check_More(res.data);
        }
      });
    },
    //加载更多的数据
    searchMore() {
      if (!this.hasMore) {
        return;
      }
      this.page++;
      this.search();
    },
    // 从新计算scroll的高度
    refresh() {
      this.$refs.suggest.refresh();
    },
    //   检查是否还有更多的数据
    check_More(data) {
      const song = data.song;
      if (song.list === [] || song.curnum + song.curpage * n > song.totalnum) {
        this.hasMore = false;
      }
    },
    //处理请求的数据的返回结果
    _normalrizeResult(data) {
      let ret = [];
      if (data.zhida && data.zhida.type) {
        ret.push({ ...data.zhida.zhida_singer, ...{ type: TYPE_SINGER } });
      }
      if (data.song) {
        ret = ret.concat(this._normalrizeSongs(data.song.list));
      }
      return ret;
    },
    _normalrizeSongs(list) {
      let ret = [];
      list.forEach(musicData => {
        if (musicData.id && musicData.album.mid) {
          ret.push(createResultSong(musicData));
        }
      });
      return ret;
    },
    getIconCls(item) {
      if (item.type === TYPE_SINGER) {
        return "iconfont icon-geshou";
      } else {
        return "iconfont icon-yinyue";
      }
    },
    getname(item) {
      if (item.type === TYPE_SINGER) {
        return item.singerName;
      } else {
        return `${item.name}-${item.singer}`;
      }
    },
    //点击跳转到歌手详情页或者添加歌曲到播放列表
    SelectItem(item) {
      if (item.type === TYPE_SINGER) {
        const singerItem = new SingerResult({
          id: item.singerMID,
          name: item.singerName,
          avatar: item.singerPic
        });
        this.$router.push({
          path: `/search/${singerItem.id}`
        });
        this.setSinger(singerItem);
      } else {
        getMusicVkey(item.mid).then(res => {
          if (res.code === ERR_OK) {
            let pcurl = res.req_0.data.midurlinfo[0].purl;
              item.url = `http://aqqmusic.tc.qq.com/amobile.music.tc.qq.com/${pcurl}`;
          } else {
            console.log("获取vkey失败");
          }
        });
        this.insertSong(item);
      }
      this.$emit("selectSearch");
    },
    listScroll() {
      this.$emit("listScroll");
    },
    ...mapMutations({
      setSinger: "SET_SINGER"
    }),
    ...mapActions(["insertSong"])
  },
  watch: {
    query(newquery) {
      //监听query的变化
      if (!newquery) {
        this.result = [];
      }
      this.changeQuery = true;
      this.search();
    }
  }
};
</script>
<style lang="stylus">
@import '../../common/stylus/variable.styl';
@import '../../common/stylus/mixin';

.suggest {
  height: 100%;
  overflow: hidden;

  .suggest-list {
    height: 100%;
    padding: 0 30px;

    .suggest-item {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
    }

    .iconfont {
      flex: 0 0 30px;
      width: 30px;
    }

    [class*='icon-'] {
      font-size: 20px;
      color: $color-theme;
    }

    .name {
      flex: 1;
      font-size: $font-size-medium;
      color: $color-text-d;
      overflow: hidden;

      .text {
        no-wrap();
      }
    }
  }

  .no-result-wrapper {
    position: absolute;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
  }

  .loading {
    display: flex;
    justify-content: center;
  }
}
</style>